package com.arvin.faceDetect.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioGroup
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.arvin.faceDetect.R
import com.arvin.faceDetect.databinding.FragmentRecognitionSettingsBinding
import com.arvin.faceDetect.utils.Settings
import com.google.android.material.appbar.MaterialToolbar
import com.google.mlkit.vision.face.FaceDetectorOptions

class RecognitionSettingsFragment : Fragment() {
    private var _binding: FragmentRecognitionSettingsBinding? = null
    private val binding get() = _binding!!

    private lateinit var toolbar: MaterialToolbar
    private lateinit var rgPerformanceMode: RadioGroup
    private lateinit var sbMinFaceSize: SeekBar
    private lateinit var tvMinFaceSize: TextView
    private lateinit var switchTracking: SwitchCompat
    private lateinit var sbRecognitionThreshold: SeekBar
    private lateinit var tvRecognitionThreshold: TextView
    private lateinit var sbMinConfirmations: SeekBar
    private lateinit var tvMinConfirmations: TextView
    private lateinit var sbMaxFaceSize: SeekBar
    private lateinit var tvMaxFaceSize: TextView
    private lateinit var sbRecognitionInterval: SeekBar
    private lateinit var tvRecognitionInterval: TextView

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecognitionSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initViews(view)
        setupToolbar()
        loadSettings()
        setupListeners()
    }

    private fun initViews(view: View) {
        toolbar = view.findViewById(R.id.toolbar)
        rgPerformanceMode = view.findViewById(R.id.rgPerformanceMode)
        sbMinFaceSize = view.findViewById(R.id.sbMinFaceSize)
        tvMinFaceSize = view.findViewById(R.id.tvMinFaceSize)
        switchTracking = view.findViewById(R.id.switchTracking)
        sbRecognitionThreshold = view.findViewById(R.id.sbRecognitionThreshold)
        tvRecognitionThreshold = view.findViewById(R.id.tvRecognitionThreshold)
        sbMinConfirmations = view.findViewById(R.id.sbMinConfirmations)
        tvMinConfirmations = view.findViewById(R.id.tvMinConfirmations)
        sbMaxFaceSize = view.findViewById(R.id.sbMaxFaceSize)
        tvMaxFaceSize = view.findViewById(R.id.tvMaxFaceSize)
        sbRecognitionInterval = view.findViewById(R.id.sbRecognitionInterval)
        tvRecognitionInterval = view.findViewById(R.id.tvRecognitionInterval)
    }

    private fun setupToolbar() {
        toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
    }

    private fun loadSettings() {
        val performanceMode = Settings.getRecognitionPerformanceMode(requireContext())
        rgPerformanceMode.check(
            if (performanceMode == FaceDetectorOptions.PERFORMANCE_MODE_FAST) {
                R.id.rbFastMode
            } else {
                R.id.rbAccurateMode
            }
        )

        val minFaceSize = Settings.getRecognitionMinFaceSize(requireContext())
        val progress = ((minFaceSize - 0.1f) * 100).toInt()
        sbMinFaceSize.progress = progress
        updateMinFaceSizeText(minFaceSize)

        val maxFaceSize = Settings.getMaxFaceSize(requireContext())
        val maxProgress = ((maxFaceSize - 0.1f) * 100).toInt()
        sbMaxFaceSize.progress = maxProgress
        updateMaxFaceSizeText(maxFaceSize)

        switchTracking.isChecked = Settings.isRecognitionTrackingEnabled(requireContext())

        val threshold = Settings.getRecognitionThreshold(requireContext())
        val thresholdProgress = ((threshold - 0.5f) * 100).toInt()
        sbRecognitionThreshold.progress = thresholdProgress
        updateRecognitionThresholdText(threshold)

        val minConfirmations = Settings.getMinConfirmations(requireContext())
        sbMinConfirmations.progress = minConfirmations - 2 // 最小值从2开始
        updateMinConfirmationsText(minConfirmations)

        val recognitionInterval = Settings.getRecognitionInterval(requireContext())
        sbRecognitionInterval.progress = recognitionInterval - 1 // 最小值从1开始
        updateRecognitionIntervalText(recognitionInterval)
    }

    private fun setupListeners() {
        rgPerformanceMode.setOnCheckedChangeListener { _, checkedId ->
            val mode = if (checkedId == R.id.rbFastMode) {
                FaceDetectorOptions.PERFORMANCE_MODE_FAST
            } else {
                FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE
            }
            Settings.setRecognitionPerformanceMode(requireContext(), mode)
        }

        sbMinFaceSize.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val value = 0.1f + progress / 100f
                updateMinFaceSizeText(value)
                if (fromUser) {
                    Settings.setRecognitionMinFaceSize(requireContext(), value)
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        sbMaxFaceSize.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val value = 0.1f + progress / 100f
                updateMaxFaceSizeText(value)
                if (fromUser) {
                    Settings.setMaxFaceSize(requireContext(), value)
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        switchTracking.setOnCheckedChangeListener { _, isChecked ->
            Settings.setRecognitionTrackingEnabled(requireContext(), isChecked)
        }

        sbMinConfirmations.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val value = progress + 2 // 最小值从2开始
                updateMinConfirmationsText(value)
                if (fromUser) {
                    Settings.setMinConfirmations(requireContext(), value)
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        sbRecognitionInterval.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val value = progress + 1 // 最小值从1开始
                updateRecognitionIntervalText(value)
                if (fromUser) {
                    Settings.setRecognitionInterval(requireContext(), value)
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun updateMinFaceSizeText(value: Float) {
        tvMinFaceSize.text = "当前值: ${String.format("%.0f", value * 100)}%"
    }

    private fun updateMaxFaceSizeText(value: Float) {
        tvMaxFaceSize.text = "当前值: ${String.format("%.0f", value * 100)}%"
    }

    private fun updateRecognitionThresholdText(value: Float) {
        tvRecognitionThreshold.text = "当前值: ${String.format("%.2f", value)}"
    }

    private fun updateMinConfirmationsText(value: Int) {
        tvMinConfirmations.text = "当前值: ${value}帧"
    }

    private fun updateRecognitionIntervalText(value: Int) {
        tvRecognitionInterval.text = "当前值: ${value}秒"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 